package com.wclass.controller.app;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Maps;
import com.wclass.common.DateUtil;
import com.wclass.common.ReturnObject;
import com.wclass.entity.CouresOrder;
import com.wclass.entity.UserSettlement;
import com.wclass.interceptor.BaseContextHandler;
import com.wclass.service.ICouresOrderService;
import com.wclass.service.IUserSettlementService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 结算记录表 前端控制器
 * </p>
 *
 * @author SEN
 * @since 2019-03-12
 */
@RestController
@Api(description = "结算记录")
@RequestMapping("/userSettlement")
public class UserSettlementController {

    @Autowired
    private IUserSettlementService iUserSettlementService;
    @Autowired
    private ICouresOrderService iCouresOrderService;

    @ApiOperation("获取结算数据")
    @RequestMapping(value = "/getSettlementList", method = RequestMethod.POST)
    public ReturnObject<Map<String, Object>> getSettlementList(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                               @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                               @ApiParam("结算状态，全部不传，0：已冻结，1：待结算，2：已结算)") Integer type){
        Map<String, Object> map = Maps.newHashMap();
        map.put("expectMoney", 0);
        map.put("settledMoney", 0);
        EntityWrapper<UserSettlement> ew = new EntityWrapper<>();
        if (type != null)
            ew.eq("type", type);
        ew.eq("user_id", BaseContextHandler.getUserID());
        ew.orderBy("crt_time", false);
        Page<UserSettlement> pageObj = iUserSettlementService.selectPage(new Page<>(offset, limit), ew);
        map.put("total", pageObj.getTotal());
        map.put("page", pageObj.getPages());
        map.put("list", pageObj.getRecords());

        for (UserSettlement userSettlement : pageObj.getRecords()) {
            if (userSettlement.getTime().equals(DateUtil.format(new Date(), "yyyy-MM"))) {
                if (userSettlement.getType() == 2) {
                    map.put("settledMoney", userSettlement.getMoney());
                } else {
                    map.put("expectMoney", userSettlement.getMoney().add(new BigDecimal(map.get("expectMoney").toString())));
                }
            }
        }

        return new ReturnObject<>(0, "获取成功", map);
    }

    @ApiOperation("获取结算课程列表")
    @RequestMapping(value = "/getSettleMonthList", method = RequestMethod.POST)
    public ReturnObject<Map<String, Object>> getSettleMonthList(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                                @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                                @ApiParam("结算id)") Long settlementId){
        Map<String, Object> ret = Maps.newHashMap();

        UserSettlement userSettlement = iUserSettlementService.selectById(settlementId);
        ret.put("userSettlement", userSettlement);
        EntityWrapper<CouresOrder> ew = new EntityWrapper<>();
        ew.eq("c.user_id", userSettlement.getUserId());
        ew.like("c.crt_time", userSettlement.getTime());
        if (userSettlement.getType() == 2)
            ew.eq("c.settlement_state", 2);
        else
            ew.eq("c.settlement_state", 1);
        Page<Map<String, Object>> pageObj = iCouresOrderService.selectCourseSettleCountList(new Page<>(offset, limit), ew);
        ret.put("total", pageObj.getTotal());
        ret.put("page", pageObj.getPages());
        ret.put("list", pageObj.getRecords());
        for (Map<String, Object> map : pageObj.getRecords()) {
            //订单结算金额 = 订单金额 - 服务费用 - 退款费用，服务费用 = 订单金额 * 服务费率（10%）
            BigDecimal orderSettleMoney = BigDecimal.valueOf(Long.parseLong(map.get("totalAmount").toString()))
                    .subtract(BigDecimal.valueOf(Double.parseDouble(map.get("totalServeMoney").toString())))
                    .subtract(BigDecimal.valueOf(Double.parseDouble(map.get("totalRefundMoney").toString())));
            map.put("settleMoney", orderSettleMoney);
        }

        return new ReturnObject<>(0, "获取成功", ret);
    }

    @ApiOperation("获取课程结算订单列表")
    @RequestMapping(value = "/getCourseOrderSettleList", method = RequestMethod.POST)
    public ReturnObject<List<CouresOrder>> getCourseOrderSettleList(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                              @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                              @ApiParam("课程id)") @RequestParam Long courseInfoId,
                                                              @ApiParam("月份时间，yyyy-MM)") @RequestParam String time,
                                                              @ApiParam("结算状态，0：已冻结、未结算，1：待结算，2：已结算)") @RequestParam Integer type){
        EntityWrapper<CouresOrder> ew = new EntityWrapper<>();
        ew.orderBy("info.crt_time", false);
        ew.eq("info.user_id", BaseContextHandler.getUserID());
        ew.eq("info.course_info_id", courseInfoId);
        ew.eq("info.settlement_state", type);
        ew.like("info.crt_time", time);
        Page<CouresOrder> obj = iCouresOrderService.selectPage(new Page<>(offset, limit), ew);
        for (CouresOrder couresOrder : obj.getRecords()) {
            //订单结算金额 = 订单金额 - 服务费用 - 退款费用，服务费用 = 订单金额 * 服务费率（10%）
            BigDecimal orderSettleMoney = BigDecimal.valueOf(couresOrder.getAmount())
                    .subtract(couresOrder.getServeMoney()).subtract(couresOrder.getRefundMoney());
            couresOrder.setSettleMoney(orderSettleMoney);
        }

        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

}

